﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootAreaSensor : MonoBehaviour
{    
    public Hashtable monsterTable;
    public GameObject curTarget;
    private float timer = 0.5f;
    private Transform player;

    private void Awake()
    {
        player = transform.parent;
        monsterTable = new Hashtable();
        curTarget = null;
    }

    // Start is called before the first frame update
    void Start()
    {        
    }

    // Update is called once per frame
    void Update()
    {
        if (timer < 0)
        {
            if (curTarget == null)
            {
                GameObject newTarget = null;
                float distance = 100000f;
                foreach (DictionaryEntry entry in monsterTable)
                {
                    GameObject tem = entry.Value as GameObject;
                    float deltx = tem.transform.localPosition.x - player.localPosition.x;
                    float delty = tem.transform.localPosition.y - player.localPosition.y;
                    float newDistance = deltx * deltx + delty * delty;
                    if (newDistance < distance) {
                        distance = newDistance;
                        newTarget = tem;
                    }
                }
                curTarget = newTarget;
                if (curTarget != null) {
                    curTarget.transform.Find("shoot_glass").gameObject.SetActive(true);
                }
            }
            timer = 0.5f;
        }
        timer -= Time.deltaTime;
    }    

    private void OnTriggerEnter2D(Collider2D collision)
    {        
        GameObject monster = collision.gameObject;
        monsterTable.Add(monster.GetHashCode(), monster);
        //if (curTarget == null) {
        //    curTarget = monster;
        //    curTarget.transform.Find("shoot_glass").gameObject.SetActive(true);
        //}

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        GameObject monster = collision.gameObject;        
        monsterTable.Remove(monster.GetHashCode());
        if (monster == curTarget) {
            curTarget.transform.Find("shoot_glass").gameObject.SetActive(false);
            curTarget = null;
        }
    }

    public void HurtTarget(int hurt) {
        if (curTarget != null) {
            curTarget.SendMessage("GetHurt", hurt);
        }
    }
}
